<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" class="search-form" label-width="68px"
             size="mini">
      <el-form-item v-for="item in searchItems" :key="item.prop" :label="item.label" :prop="item.prop">
        <el-input v-model="queryParams[item.prop]" :placeholder="`请输入${item.label}`" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item class="search-buttons">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="action-toolbar">
      <div class="left-buttons">
        <el-button v-for="btn in buttons"
                   :key="btn.type"
                   v-hasPermi="btn.perm"
                   :disabled="btn.disabled"
                   :icon="btn.icon"
                   :type="btn.type"
                   class="action-button"
                   plain
                   size="mini"
                   @click="btn.handler">
          {{ btn.text }}
        </el-button>
      </div>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
    </div>

    <!-- 游戏列表 -->
    <div v-loading="loading" class="game-list-container">
      <div class="game-grid">
        <div v-for="item in gameList" :key="item.id" class="game-card-wrapper">
          <el-popover placement="top" popper-class="game-popover" trigger="hover" width="200">
            <div class="popover-content">
              <div class="popover-title">{{ item.gameName || '未命名游戏' }}</div>
              <div class="popover-remark">{{ item.remark || '暂无备注' }}</div>
            </div>
            <el-card slot="reference" class="game-card" shadow="hover">
              <div class="game-content">
                <div class="game-image-wrapper">
                  <el-image :src="processImageUrl(item.icon)" class="game-image" fit="contain">
                    <div slot="error" class="image-placeholder">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </div>
                <div class="game-info">
                  <div :title="item.gameName" class="game-name">{{ item.gameName || '未命名游戏' }}</div>
                  <div :title="item.remark" class="game-remark">{{ item.remark || '暂无备注' }}</div>
                  <div class="game-actions">
                    <el-tag :type="item.status === '0' ? 'success' : 'info'" class="status-tag" size="mini">
                      {{ item.status === '0' ? '正常' : '停用' }}
                    </el-tag>
                    <div class="action-buttons">
                      <el-button v-hasPermi="['game:game:remove']"
                                 class="edit-btn"
                                 icon="el-icon-edit"
                                 size="mini"
                                 type="text"
                                 @click.stop="handleUpdate(item)">
                        编辑
                      </el-button>
                      <el-button v-hasPermi="['game:game:remove']"
                                 class="delete-btn"
                                 icon="el-icon-delete"
                                 size="mini"
                                 type="text"
                                 @click.stop="handleDelete(item)">
                        删除
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-popover>
        </div>
      </div>

      <!-- 空状态提示 -->
      <div v-if="gameList.length === 0 && !loading" class="empty-state">
        <div class="empty-icon-wrapper">
          <i class="el-icon-video-play"></i>
        </div>
        <p class="empty-text">暂无游戏数据</p>
        <el-button icon="el-icon-plus" size="small" type="primary" @click="handleAdd">添加游戏</el-button>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <pagination v-show="total>0"
                  :limit.sync="queryParams.pageSize"
                  :page.sync="queryParams.pageNum"
                  :total="total"
                  @pagination="getList"/>
    </div>

    <!-- 弹窗表单 -->
    <el-dialog :show-close="false"
               :title="title"
               :visible.sync="open"
               append-to-body
               center
               custom-class="game-dialog"
               width="400px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="upload-container">
          <div class="icon-uploader-wrapper">
            <div :class="{'has-image': imageUrl}" class="icon-uploader" @click="triggerFileInput">
              <img v-if="imageUrl" :src="processImageUrl(imageUrl)" alt="游戏图标" class="icon-preview">
              <div v-else class="upload-placeholder">
                <i class="el-icon-plus"></i>
                <span>点击上传图标</span>
              </div>
            </div>
            <input ref="fileInput" accept="image/*" style="display: none" type="file" @change="handleFileChange">
          </div>
        </div>

        <el-form-item label="游戏名称" prop="gameName">
          <el-input v-model="form.gameName" placeholder="请输入游戏名称" size="mini"/>
        </el-form-item>
        <el-form-item label="游戏模板" prop="gameTemplateId">
          <el-select v-model="form.gameTemplateId" placeholder="请选择模板" size="mini" style="width: 100%">
            <el-option
              v-for="item in gameTemplateList"
              :key="item.id"
              :label="item.templateName"
              :value="item.id"
              size="mini">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" :rows="2" placeholder="请输入备注" size="mini" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="cancel">取 消</el-button>
        <el-button :loading="submitLoading" size="mini" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addGame, delGame, getGame, listGame, updateGame, uploadIcon} from "@/api/game/game";
import {listTemplate} from "@/api/template/game";

export default {
  name: "Game",
  data() {
    return {
      loading: true,
      submitLoading: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      gameList: [],
      gameTemplateList: [],
      title: "",
      open: false,
      imageUrl: "", // 临时存储上传图片的URL
      imageFile: null, // 存储上传的文件对象
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gameTemplateId: null,
        gameName: null,
        status: null,
        icon: null,
      },
      form: {},
      rules: {
        gameName: [
          {required: true, message: "游戏名称不能为空", trigger: "blur"}
        ],
        gameTemplateId: [
          {required: true, message: "请选择游戏模板", trigger: "change"}
        ]
      },
      searchItems: [
        {label: '模板名称', prop: 'templateName'},
        {label: '游戏名称', prop: 'gameName'}
      ],
      buttons: [
        {type: 'primary', text: '新增', icon: 'el-icon-plus', handler: this.handleAdd, perm: ['system:game:add']},
        {
          type: 'success',
          text: '修改',
          icon: 'el-icon-edit',
          handler: this.handleUpdate,
          disabled: this.single,
          perm: ['system:game:edit']
        },
        {
          type: 'danger',
          text: '删除',
          icon: 'el-icon-delete',
          handler: this.handleDelete,
          disabled: this.multiple,
          perm: ['system:game:remove']
        },
        {
          type: 'warning',
          text: '导出',
          icon: 'el-icon-download',
          handler: this.handleExport,
          perm: ['system:game:export']
        }
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 处理图片URL，判断是否需要添加前缀
    processImageUrl(url) {
      if (!url) return '';

      // 如果是本地预览的blob URL或者已经是完整URL，直接返回
      if (url.startsWith('blob:') || url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }

      // 否则添加API前缀
      return `${process.env.VUE_APP_BASE_API}/${url}`;
    },

    // 触发文件选择
    triggerFileInput() {
      this.$refs.fileInput.click();
    },

    // 处理文件选择变化
    handleFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;

      // 验证文件类型和大小
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
        return;
      }

      this.imageFile = file;
      // 创建本地预览URL (blob:开头)
      this.imageUrl = URL.createObjectURL(file);
    },

    // 上传图片到服务器
    async uploadImage() {
      if (!this.imageFile) {
        // 如果没有新选择的图片，直接返回原来的图标URL
        return this.form.icon;
      }

      try {
        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', this.imageFile);

        // 调用上传API
        const response = await uploadIcon(formData);
        return response.url;
      } catch (error) {
        this.$message.error('图片上传失败');
        console.error('上传失败:', error);
        return null;
      }
    },

    /** 查询游戏列表 */
    getList() {
      this.loading = true;
      listGame(this.queryParams).then(response => {
        this.gameList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        gameTemplateId: null,
        gameName: null,
        status: "0",
        icon: null,
        delFlag: null,
        createTime: null,
        updateTime: null,
        remark: null
      };
      this.imageUrl = "";
      this.imageFile = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getGameTemplateList()
      this.open = true;
      this.title = "添加游戏";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.getGameTemplateList()
      getGame(id).then(response => {
        this.form = response.data;
        this.imageUrl = this.form.icon;
        this.open = true;
        this.title = "修改游戏";
      });
    },
    getGameTemplateList() {
      listTemplate().then(res => {
        this.gameTemplateList = res.rows;
      })
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          try {
            this.submitLoading = true;
            // 先上传图片
            const iconUrl = await this.uploadImage();
            if (iconUrl) {
              this.form.icon = iconUrl;
            }

            // 然后提交表单数据
            if (this.form.id != null) {
              await updateGame(this.form);
              this.$modal.msgSuccess("修改成功");
            } else {
              await addGame(this.form);
              this.$modal.msgSuccess("新增成功");
            }

            this.open = false;
            this.getList();
          } catch (error) {
            console.error("提交失败:", error);
            this.$modal.msgError("操作失败");
          } finally {
            this.submitLoading = false;
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除游戏编号为"' + ids + '"的数据项？').then(function () {
        return delGame(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/game/export', {
        ...this.queryParams
      }, `game_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>

<style scoped>
/* 全局动画定义 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes float {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-5px);
  }
  100% {
    transform: translateY(0px);
  }
}

/* 容器样式 */
.app-container {
  padding: 12px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
  border-radius: 4px;
}

/* 搜索表单样式 */
.search-form {
  background: white;
  padding: 12px;
  border-radius: 6px;
  box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 12px;
}

.search-buttons {
  margin-left: 8px;
}

/* 操作工具栏 */
.action-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  background: white;
  padding: 10px 12px;
  border-radius: 6px;
  box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.05);
}

.left-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-button {
  transition: all 0.2s;
}

.action-button:hover {
  transform: translateY(-2px);
}

/* 游戏列表容器 */
.game-list-container {
  background: white;
  border-radius: 6px;
  padding: 12px;
  box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.05);
  min-height: 300px;
  position: relative;
}

.game-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 16px;
  animation: fadeIn 0.4s ease-out;
}

/* 游戏卡片样式 */
.game-card-wrapper {
  animation: fadeIn 0.4s ease-out;
}

.game-card {
  height: 100%;
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  border: none;
}

.game-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

.game-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.game-image-wrapper {
  height: 140px;
  background-color: #f8f9fa;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
}

.game-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  padding: 10px;
  transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.game-card:hover .game-image {
  transform: scale(1.05);
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.image-placeholder i {
  font-size: 36px;
  color: #dcdfe6;
}

.game-info {
  padding: 10px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.game-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.3;
}

.game-remark {
  font-size: 12px;
  color: #606266;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  flex: 1;
  min-height: 34px;
}

.game-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.status-tag {
  font-size: 10px;
  padding: 0 6px;
  height: 20px;
  line-height: 18px;
  border-radius: 3px;
}

.action-buttons {
  display: flex;
  gap: 4px;
}

.edit-btn, .delete-btn {
  padding: 2px 4px;
  transition: all 0.2s;
}

.edit-btn {
  color: #409EFF;
}

.edit-btn:hover {
  color: #66b1ff;
  transform: scale(1.05);
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
  transform: scale(1.05);
}

/* 空状态样式 */
.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  animation: fadeIn 0.4s ease-out;
}

.empty-icon-wrapper {
  font-size: 60px;
  color: #dcdfe6;
  margin-bottom: 15px;
  animation: float 2s infinite ease-in-out;
}

.empty-text {
  font-size: 14px;
  color: #909399;
  margin-bottom: 15px;
}

/* 分页容器 */
.pagination-container {
  margin-top: 12px;
  display: flex;
  justify-content: center;
}

/* 弹窗样式 */
::v-deep .game-dialog {
  border-radius: 8px;
  overflow: hidden;
}

::v-deep .game-dialog .el-dialog__header {
  background: #f5f7fa;
  padding: 12px 15px;
  text-align: center;
}

::v-deep .game-dialog .el-dialog__title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

::v-deep .game-dialog .el-dialog__body {
  padding: 20px 15px 5px;
}

::v-deep .game-dialog .el-dialog__footer {
  padding: 5px 15px 15px;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.dialog-footer .el-button {
  min-width: 80px;
  transition: all 0.2s;
}

.dialog-footer .el-button:hover {
  transform: translateY(-2px);
}

/* 上传图标样式 */
.upload-container {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.icon-uploader-wrapper {
  width: 100%;
  display: flex;
  justify-content: center;
}

.icon-uploader {
  width: 120px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  background-color: #fafafa;
}

.icon-uploader:hover {
  border-color: #409EFF;
  background-color: #ecf5ff;
}

.icon-uploader.has-image {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.upload-placeholder i {
  font-size: 30px;
  margin-bottom: 8px;
  transition: transform 0.2s;
}

.icon-uploader:hover .upload-placeholder i {
  transform: scale(1.1);
  color: #409EFF;
}

.upload-placeholder span {
  font-size: 12px;
}

.icon-preview {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.2s;
}

.icon-uploader.has-image:hover .icon-preview {
  transform: scale(1.05);
}

/* 弹窗内容样式 */
.popover-content {
  padding: 12px;
}

.popover-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  word-break: break-all;
}

.popover-remark {
  font-size: 12px;
  color: #606266;
  word-break: break-all;
  line-height: 1.5;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .game-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 12px;
  }

  .game-image-wrapper {
    height: 120px;
  }

  .game-name {
    font-size: 13px;
  }

  .game-remark {
    font-size: 11px;
    min-height: 30px;
  }
}
</style>
